/**
 * 前端代码解析工具 - 支持React、Vue、JavaScript、CSS等
 */
export class FrontendParser {
    
    /**
     * 检测React Class组件
     */
    static isReactClassComponent(content: string): boolean {
        return /class\s+\w+\s+extends\s+(React\.)?Component/.test(content) ||
               /class\s+\w+\s+extends\s+(React\.)?PureComponent/.test(content);
    }

    /**
     * 检测React Function组件
     */
    static isReactFunctionComponent(content: string): boolean {
        return /function\s+\w+\s*\([^)]*\)\s*\{[\s\S]*return\s*\([\s\S]*</.test(content) ||
               /const\s+\w+\s*=\s*\([^)]*\)\s*=>\s*\{[\s\S]*return\s*\([\s\S]*</.test(content) ||
               /const\s+\w+\s*=\s*\([^)]*\)\s*=>\s*\([\s\S]*</.test(content);
    }

    /**
     * 检测Vue 2组件
     */
    static isVue2Component(content: string): boolean {
        return /export\s+default\s*\{[\s\S]*data\s*\(\s*\)\s*\{/.test(content) ||
               /Vue\.component\s*\(\s*['"`]/.test(content) ||
               /<template>[\s\S]*<\/template>/.test(content);
    }

    /**
     * 检测Vue 3 Composition API
     */
    static isVue3CompositionComponent(content: string): boolean {
        return /setup\s*\(\s*\)\s*\{/.test(content) ||
               /import\s*\{[\s\S]*setup[\s\S]*\}\s*from\s*['"`]vue['"`]/.test(content);
    }

    /**
     * 提取React Class组件的方法
     */
    static extractReactClassMethods(content: string): Array<{
        name: string;
        startLine: number;
        endLine: number;
        isLifecycle: boolean;
        content: string;
    }> {
        const methods: Array<{
            name: string;
            startLine: number;
            endLine: number;
            isLifecycle: boolean;
            content: string;
        }> = [];
        
        const lines = content.split('\n');
        const lifecycleMethods = new Set([
            'componentDidMount', 'componentDidUpdate', 'componentWillUnmount',
            'componentDidCatch', 'getDerivedStateFromError', 'getSnapshotBeforeUpdate',
            'shouldComponentUpdate', 'render'
        ]);

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            // 匹配方法定义: methodName = () => { 或 methodName() {
            const methodMatch = line.match(/^(\w+)\s*[=:]\s*\([^)]*\)\s*=>\s*\{|^(\w+)\s*\([^)]*\)\s*\{/);
            
            if (methodMatch) {
                const methodName = methodMatch[1] || methodMatch[2];
                const startLine = i + 1;
                const endLine = this.findMethodEndLine(lines, i);
                
                if (endLine > startLine) {
                    methods.push({
                        name: methodName,
                        startLine,
                        endLine,
                        isLifecycle: lifecycleMethods.has(methodName),
                        content: lines.slice(i, endLine).join('\n')
                    });
                }
            }
        }

        return methods;
    }

    /**
     * 检测可以转换为Hooks的模式
     */
    static analyzeHooksOpportunities(content: string): Array<{
        type: 'state' | 'effect' | 'ref' | 'context' | 'memo';
        suggestion: string;
        line: number;
        replacement: string;
    }> {
        const opportunities: Array<{
            type: 'state' | 'effect' | 'ref' | 'context' | 'memo';
            suggestion: string;
            line: number;
            replacement: string;
        }> = [];
        
        const lines = content.split('\n');
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            // 检测state使用
            if (line.includes('this.state') || line.includes('this.setState')) {
                opportunities.push({
                    type: 'state',
                    suggestion: '使用useState Hook替代class state',
                    line: i + 1,
                    replacement: 'const [stateName, setStateName] = useState(initialValue);'
                });
            }
            
            // 检测生命周期方法
            if (line.includes('componentDidMount')) {
                opportunities.push({
                    type: 'effect',
                    suggestion: '使用useEffect Hook替代componentDidMount',
                    line: i + 1,
                    replacement: 'useEffect(() => { /* 副作用逻辑 */ }, []);'
                });
            }
            
            if (line.includes('componentDidUpdate')) {
                opportunities.push({
                    type: 'effect',
                    suggestion: '使用useEffect Hook替代componentDidUpdate',
                    line: i + 1,
                    replacement: 'useEffect(() => { /* 副作用逻辑 */ }, [dependencies]);'
                });
            }
            
            // 检测ref使用
            if (line.includes('React.createRef()') || line.includes('createRef()')) {
                opportunities.push({
                    type: 'ref',
                    suggestion: '使用useRef Hook替代createRef',
                    line: i + 1,
                    replacement: 'const refName = useRef(null);'
                });
            }
            
            // 检测context使用
            if (line.includes('.contextType') || line.includes('Context.Consumer')) {
                opportunities.push({
                    type: 'context',
                    suggestion: '使用useContext Hook简化Context使用',
                    line: i + 1,
                    replacement: 'const contextValue = useContext(YourContext);'
                });
            }
        }
        
        return opportunities;
    }

    /**
     * 检测可以提取的自定义Hook
     */
    static suggestCustomHooks(content: string): Array<{
        name: string;
        description: string;
        logic: string[];
        suggestedHookName: string;
    }> {
        const customHooks: Array<{
            name: string;
            description: string;
            logic: string[];
            suggestedHookName: string;
        }> = [];
        
        const lines = content.split('\n');
        
        // 检测API调用模式
        const apiCallPattern = /fetch\s*\(|axios\.|\.get\(|\.post\(|\.put\(|\.delete\(/;
        let apiLogicLines: string[] = [];
        let startApiLogic = false;
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            
            if (apiCallPattern.test(line)) {
                startApiLogic = true;
                apiLogicLines = [line];
            } else if (startApiLogic && (line.includes('.then(') || line.includes('.catch(') || line.includes('setLoading') || line.includes('setError'))) {
                apiLogicLines.push(line);
            } else if (startApiLogic && line.trim() === '') {
                // 空行结束API逻辑收集
                if (apiLogicLines.length >= 3) {
                    customHooks.push({
                        name: 'API调用逻辑',
                        description: '将API调用、loading和error处理提取为自定义Hook',
                        logic: apiLogicLines,
                        suggestedHookName: 'useApiCall'
                    });
                }
                startApiLogic = false;
                apiLogicLines = [];
            }
        }
        
        // 检测表单处理模式
        if (content.includes('onChange') && content.includes('value') && content.includes('state')) {
            customHooks.push({
                name: '表单处理逻辑',
                description: '将表单状态管理和验证提取为自定义Hook',
                logic: ['表单状态管理', '输入验证', '提交处理'],
                suggestedHookName: 'useForm'
            });
        }
        
        return customHooks;
    }

    /**
     * 检测Vue组件可以转换为Composition API的部分
     */
    static analyzeVueCompositionOpportunities(content: string): Array<{
        type: 'data' | 'computed' | 'methods' | 'lifecycle';
        suggestion: string;
        original: string;
        replacement: string;
    }> {
        const opportunities: Array<{
            type: 'data' | 'computed' | 'methods' | 'lifecycle';
            suggestion: string;
            original: string;
            replacement: string;
        }> = [];
        
        // 检测data属性
        const dataMatch = content.match(/data\s*\(\s*\)\s*\{[\s\S]*?return\s*\{([\s\S]*?)\}/);
        if (dataMatch) {
            opportunities.push({
                type: 'data',
                suggestion: '使用ref和reactive替代data函数',
                original: dataMatch[0],
                replacement: 'const state = reactive({ /* data properties */ });'
            });
        }
        
        // 检测computed属性
        const computedMatch = content.match(/computed\s*:\s*\{([\s\S]*?)\}/);
        if (computedMatch) {
            opportunities.push({
                type: 'computed',
                suggestion: '使用computed函数替代computed对象',
                original: computedMatch[0],
                replacement: 'const computedValue = computed(() => { /* computation */ });'
            });
        }
        
        // 检测methods
        const methodsMatch = content.match(/methods\s*:\s*\{([\s\S]*?)\}/);
        if (methodsMatch) {
            opportunities.push({
                type: 'methods',
                suggestion: '在setup函数中定义方法',
                original: methodsMatch[0],
                replacement: 'const methodName = () => { /* method logic */ };'
            });
        }
        
        return opportunities;
    }

    /**
     * 检测CSS/SCSS可以优化的地方
     */
    static analyzeCSSOptimizations(content: string, type: 'css' | 'scss' = 'css'): Array<{
        type: 'bem' | 'nesting' | 'variables' | 'mixins';
        suggestion: string;
        line: number;
        original: string;
        improved: string;
    }> {
        const optimizations: Array<{
            type: 'bem' | 'nesting' | 'variables' | 'mixins';
            suggestion: string;
            line: number;
            original: string;
            improved: string;
        }> = [];
        
        const lines = content.split('\n');
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            // 检测可以使用BEM命名的情况
            if (line.match(/^\.[a-zA-Z-]+\s.*\.[a-zA-Z-]+/)) {
                optimizations.push({
                    type: 'bem',
                    suggestion: '考虑使用BEM命名约定',
                    line: i + 1,
                    original: line,
                    improved: '/* 使用 .block__element--modifier 格式 */'
                });
            }
            
            // 检测重复的颜色值
            const colorMatch = line.match(/#[0-9a-fA-F]{3,6}|rgb\(|rgba\(/);
            if (colorMatch && type === 'scss') {
                optimizations.push({
                    type: 'variables',
                    suggestion: '提取颜色为SCSS变量',
                    line: i + 1,
                    original: line,
                    improved: '$primary-color: #your-color; /* 然后使用 $primary-color */'
                });
            }
            
            // 检测可以嵌套的选择器
            if (type === 'scss' && line.startsWith('.') && lines[i + 1]?.trim().startsWith('.')) {
                const currentClass = line.match(/\.([a-zA-Z0-9-_]+)/)?.[1];
                const nextClass = lines[i + 1].match(/\.([a-zA-Z0-9-_]+)/)?.[1];
                
                if (currentClass && nextClass && nextClass.startsWith(currentClass)) {
                    optimizations.push({
                        type: 'nesting',
                        suggestion: '使用SCSS嵌套简化选择器',
                        line: i + 1,
                        original: `${line}\n${lines[i + 1]}`,
                        improved: `.${currentClass} {\n  &__${nextClass.replace(currentClass, '')} {\n    /* styles */\n  }\n}`
                    });
                }
            }
        }
        
        return optimizations;
    }

    /**
     * 检测JavaScript现代化机会
     */
    static analyzeJavaScriptModernization(content: string): Array<{
        type: 'es6-arrow' | 'destructuring' | 'template-literal' | 'async-await' | 'spread' | 'const-let';
        suggestion: string;
        line: number;
        original: string;
        modernized: string;
    }> {
        const modernizations: Array<{
            type: 'es6-arrow' | 'destructuring' | 'template-literal' | 'async-await' | 'spread' | 'const-let';
            suggestion: string;
            line: number;
            original: string;
            modernized: string;
        }> = [];
        
        const lines = content.split('\n');
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            // 检测function表达式可以转换为箭头函数
            const functionMatch = line.match(/^(?:const|let|var)\s+(\w+)\s*=\s*function\s*\([^)]*\)\s*\{/);
            if (functionMatch) {
                modernizations.push({
                    type: 'es6-arrow',
                    suggestion: '使用箭头函数替代function表达式',
                    line: i + 1,
                    original: line,
                    modernized: line.replace(/function\s*\([^)]*\)\s*\{/, '($1) => {')
                });
            }
            
            // 检测字符串连接可以用模板字符串
            if (line.includes('" + ') || line.includes("' + ")) {
                modernizations.push({
                    type: 'template-literal',
                    suggestion: '使用模板字符串替代字符串连接',
                    line: i + 1,
                    original: line,
                    modernized: '// 使用 `字符串 ${变量} 字符串` 格式'
                });
            }
            
            // 检测Promise.then可以转换为async/await
            if (line.includes('.then(') && !line.includes('await')) {
                modernizations.push({
                    type: 'async-await',
                    suggestion: '使用async/await替代Promise.then',
                    line: i + 1,
                    original: line,
                    modernized: '// 使用 const result = await promise; 格式'
                });
            }
            
            // 检测var使用
            if (line.startsWith('var ')) {
                modernizations.push({
                    type: 'const-let',
                    suggestion: '使用const/let替代var',
                    line: i + 1,
                    original: line,
                    modernized: line.replace('var ', 'const ')
                });
            }
            
            // 检测对象属性访问可以用解构
            const destructuringMatch = line.match(/const\s+(\w+)\s*=\s*(\w+)\.(\w+);?/);
            if (destructuringMatch) {
                modernizations.push({
                    type: 'destructuring',
                    suggestion: '使用解构赋值简化代码',
                    line: i + 1,
                    original: line,
                    modernized: `const { ${destructuringMatch[3]} } = ${destructuringMatch[2]};`
                });
            }
        }
        
        return modernizations;
    }

    private static findMethodEndLine(lines: string[], startIndex: number): number {
        let braceCount = 0;
        let foundOpenBrace = false;
        
        for (let i = startIndex; i < lines.length; i++) {
            const line = lines[i];
            
            for (const char of line) {
                if (char === '{') {
                    braceCount++;
                    foundOpenBrace = true;
                } else if (char === '}') {
                    braceCount--;
                    
                    if (foundOpenBrace && braceCount === 0) {
                        return i + 1;
                    }
                }
            }
        }
        
        return startIndex + 1;
    }
}